//
//  WebViewController.m
//  FundationProject
//
//  Created by Lix on 2018/7/30.
//  Copyright © 2018年 Originalee. All rights reserved.
//

#import "WebViewController.h"
#import "OAuthAPI.h"
#import "Utility.h"
#import <WebViewJavascriptBridge/WKWebViewJavascriptBridge.h>
#import <AFNetworkReachabilityManager.h>
#import <UIButton+WebCache.h>
#import "ShareModel.h"
#import "PaymentModel.h"
#import "LoginViewController.h"
#import "HttpRequest.h"
#import "TeacherModel.h"
#import "TeacherDetailViewController.h"

@interface WebViewController ()

@property (nonatomic, weak) UIProgressView *progressBar;
@property (nonatomic, strong)WKUserContentController *userContentController;
@property (strong, nonatomic) AFNetworkReachabilityManager *networkManager;
@property (strong, nonatomic) UIButton *rightItemButton;
@property (copy, nonatomic) NSString *rightButtonCallback;
@end

@implementation WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configWebView];
    [self getUserInfo];
    [self getAccessToken];
    [self nativePush];
    [self jsEcho];
    [self createNetworkManager];
    [self configRightBar];
    [self getShareData];
    [self showPaymentControl];
    [self goToLoginPage];
    [self goToTeacherPage];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
    NSLog(@"");
}

- (void)createNetworkManager {
    
    __weak typeof(self) weakself = self;
    self.networkManager = [AFNetworkReachabilityManager manager];
    [_networkManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {
            [weakself.webView reload];
        }
    }];
    [_networkManager startMonitoring];
}

#pragma mark - 创建webView
- (void)configWebView {
    //配置环境
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]init];
    self.userContentController = [[WKUserContentController alloc] init];
    configuration.userContentController = self.userContentController;
    WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
//    webView.navigationDelegate = self;
    webView.UIDelegate = self;
    //加载本地网页
//    NSURL *url = [[NSURL alloc] initWithString:@"http://192.168.1.101:8080/#/jsbridge"];
//    [webView loadRequest:[NSURLRequest requestWithURL:url]];
    
    
    [self.view addSubview:webView];
    self.webView = webView;
    self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView];
    [(WKWebViewJavascriptBridge*)self.bridge setWebViewDelegate:self];
}

#pragma mark - 获取用户信息示例 JSBridge 获取本地信息示例
- (void)getUserInfo {
    [self.bridge registerHandler:@"getUserInfo" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"get user info with: %@", data);
        NSDictionary *userInfo = @{
                                   @"name": @"lix",
                                   @"age": [NSNumber numberWithInt:21]
                                   };
        responseCallback(userInfo);
    }];
}

#pragma mark - 获取AccessToken示例
- (void)getAccessToken {
    [self.bridge registerHandler:@"getAccessToken" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSDictionary *dic = @{
                              @"accessToken": [OAuthAPI getAccessToken]
                              };
        responseCallback(dic);
    }];
}

#pragma mark - push
- (void)nativePush {
    [self.bridge registerHandler:@"nativePush" handler:^(id data, WVJBResponseCallback responseCallback) {
        [Utility push:data];
    }];
}

#pragma mark - 支付
- (void)showPaymentControl {
    __weak typeof(self) weakself = self;
    [self.bridge registerHandler:@"showPaymentControl" handler:^(id data, WVJBResponseCallback responseCallback) {
        [[PaymentModel shared] showPaymentView:data];
        [PaymentModel shared].webCon = weakself;
    }];
}

#pragma mark - 右上角按钮
- (void)configRightBar {
    __weak typeof(self) weakself = self;
    [self.bridge registerHandler:@"configRightBar" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"%@", data);
        [weakself createRightButtonItem:data];
    }];
}

#pragma mark - 分享数据
- (void)getShareData {
    /*img = "http://huashi.img.emhome.cn/attachments/profile/201809/07/i0jaQq24b08f11b8902f3fbb0f869405a04bb5.jpg";
     link = "https://baidu.com";
     title = "\U4e66\U6cd5\U7ed8\U753b\U4e00\U65e5\U4fee";*/
    [self.bridge registerHandler:@"share" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"分享数据: %@", data);
        [[ShareModel shared] showShareView:data];
    }];
}

- (void)createRightButtonItem:(NSDictionary*)dic {
    
    NSDictionary *btn = dic[@"btn"];
    if (!(btn[@"img"] == nil || (NSNull*)btn[@"img"] == [NSNull null])) {
        self.rightItemButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightItemButton.frame = CGRectMake(0, 0, 44, 44);
        [_rightItemButton setImageEdgeInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
        [_rightItemButton sd_setImageWithURL:[NSURL URLWithString:btn[@"img"]] forState:UIControlStateNormal];
    }else if (!(btn[@"title"] == nil || (NSNull*)btn[@"title"] == [NSNull null])) {
        self.rightItemButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightItemButton.titleLabel.font = [UIFont systemFontOfSize:15.0];
        _rightItemButton.frame = CGRectMake(0, 0, 30, 50);
        [_rightItemButton setTitleColor:COLOR(155, 155, 155, 1) forState:UIControlStateNormal];
        [_rightItemButton setTitle:btn[@"title"] forState:UIControlStateNormal];
    }else {
        return;
    }
    [_rightItemButton addTarget:self action:@selector(rightButtonItemPressed) forControlEvents:UIControlEventTouchUpInside];
    UIView *view = [[UIView alloc] initWithFrame:_rightItemButton.bounds];
    [view addSubview:_rightItemButton];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:view];
    [item setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:63/255.0 green:63/255.0 blue:63/255.0 alpha:1.0], NSFontAttributeName: [UIFont systemFontOfSize:15.0]} forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = item;
    self.rightButtonCallback = dic[@"callback"];
}

- (void)rightButtonItemPressed {
    [self.webView evaluateJavaScript:self.rightButtonCallback completionHandler:^(id _Nullable data, NSError * _Nullable error) {
        NSLog(@"%@", data);
    }];
}

#pragma mark - 支付完成
- (void)finishPay {
    [self.bridge callHandler:@"finishPay"];
}

#pragma mark - 登录
- (void)goToLoginPage {
    __weak typeof(self) weakself = self;
    [self.bridge registerHandler:@"goToLoginPage" handler:^(id data, WVJBResponseCallback responseCallback) {
        UINavigationController *navi = [LoginViewController loginViewController];
        [weakself presentViewController:navi animated:YES completion:nil];
    }];
}

#pragma mark - 老师详情
- (void)goToTeacherPage {
    __weak typeof(self) weakself = self;
    [self.bridge registerHandler:@"goToTeacherPage" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"%@", data);
        [HttpRequest getURL:[NSString stringWithFormat:@"%@/%@", kteacher_list, data[@"id"]] paras:nil showProgress:YES successful:^(id  _Nullable result) {
            NSLog(@"%@", result);
            NSDictionary *dic = result[@"data"];
            TeacherModel *teacher = [[TeacherModel alloc] initWithDic:dic];
            TeacherDetailViewController *detail = [[TeacherDetailViewController alloc] init];
            detail.teacher = teacher;
            [weakself.navigationController pushViewController:detail animated:YES];
        } failed:nil];
    }];
}

#pragma mark - jsBridge 调用js函数示例
- (void)jsEcho {
    [self.bridge callHandler:@"JS Echo" data:@{@"data": @"test"} responseCallback:^(id responseData) {
        NSLog(@"从js函数返回的返回值: %@", responseData);
    }];
}

#pragma WKNavigatonDelegate
// 1 页面开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"");
}
// 2 开始获取到网页内容时返回
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    NSLog(@"");
}
//3 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"");
    [_networkManager stopMonitoring];
}
//4 页面加载失败之后调用
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"");
}
// 5接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    NSLog(@"");
}

// 6在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
    //    NSLog(@"%@",navigationResponse.response.URL.absoluteString);
    //    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}
// 7在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    //    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    //    //允许跳转
    NSURL *URL = navigationAction.request.URL;
    NSString *scheme = [URL scheme];
    if ([scheme isEqualToString:@"tel"]) {
        NSString *resourceSpecifier = [URL resourceSpecifier];
        NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", resourceSpecifier];
        /// 防止iOS 10及其之后，拨打电话系统弹出框延迟出现
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @NO} completionHandler:nil];
        });
    }
    decisionHandler(WKNavigationActionPolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationActionPolicyCancel);
}
#pragma WKUIDelegate
// 创建一个新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    return [[WKWebView alloc]init];
}
// 输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler{
    completionHandler(@"http");
}
// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
    completionHandler(YES);
}
// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    NSLog(@"%@",message);
    completionHandler();
}

#pragma WKWKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"name:%@\\\\n body:%@\\\\n",message.name,message.body);
}
@end
